package com.example.vpnservicedemo.receive;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UdpSelector {
    private static Selector selector;

    private static ConcurrentLinkedQueue<RegisterData> registerQueue = new ConcurrentLinkedQueue<>();

    static {

        try {
            selector = Selector.open();
        } catch (IOException e) {
            System.out.println("UdpSelector 启动失败:" + e.getMessage());
        }

        Thread thread = new Thread(() -> {
            try {
                while (!Thread.interrupted()) {
                    // 等待事件
                    selector.select();

                    // 获取事件的迭代器
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();

                        if (key.isReadable()) {

                            // 如果事件是READ事件，处理读取数据
                            DatagramChannel dc = (DatagramChannel) key.channel();
                            UdpPipe udpPipe = (UdpPipe) key.attachment();

                            int bytesRead = dc.read(buffer);

                            if (bytesRead == -1) {
                                // 客户端关闭连接
                                udpPipe.close();
                            } else if (bytesRead > 0) {
                                buffer.flip();
                                byte[] array = new byte[bytesRead];
                                buffer.get(array);
                                udpPipe.pushData(array);
                                buffer.clear();
                            }

                        }

                        // 删除处理过的事件
                        iterator.remove();
                    }
                    RegisterData registerData = null;
                    while ((registerData = registerQueue.poll()) != null) {
                        registerData.datagramChannel.register(selector, SelectionKey.OP_READ, registerData.udpPipe);
                    }

                }

            } catch (Exception e) {
                System.out.println("UdpSelector 线程异常结束:" + e.getMessage());
                e.printStackTrace();
            }

        });
        thread.setName("UdpSelector");
        thread.start();

    }

    public static void registerRead(DatagramChannel datagramChannel, UdpPipe udpPipe) {

        RegisterData registerData = new RegisterData();
        registerData.datagramChannel = datagramChannel;
        registerData.udpPipe = udpPipe;

        registerQueue.offer(registerData);
        selector.wakeup();
    }

    static class RegisterData {
        DatagramChannel datagramChannel;
        UdpPipe udpPipe;
    }


}
